package com.tenton.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * @Author:Tenton
 * @Date: 2020/7/15 17:34
 * @Description:
 */
@WebServlet(name = "UpLoadServlet", urlPatterns = "/upLoadServlet")
public class UpLoadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置请求时编码
        request.setCharacterEncoding("utf-8");
        //设置响应编码
        response.setContentType("text/html;charset=UTF-8");
        response.setCharacterEncoding("utf-8");

        //上传
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        //判断前台的form表单中是否有multipart属性
        if (isMultipart){
            //实现类
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            //设置上传时 用到的临时文件的大小 DiskFileItemFactory
            //设置临时的缓冲文件 大小为10KB
            factory.setSizeThreshold(10240);
            //设置临时文件的目录
            factory.setRepository(new File("src\\main\\webapp\\images"));
            //控制上传单个文件的大小 20KB  ServletFileUpload
            upload.setSizeMax(20480);

            //通过parseRequest解析form中的所有请求字段，并保存到items集合中（即前台传递的imgName image此时就保存在了fileItems中）
            try {
                List<FileItem> fileItems = upload.parseRequest(request);
                Iterator<FileItem> iterator = fileItems.iterator();
                while (iterator.hasNext()) {
                    FileItem fileItem = iterator.next();
                    //因为前台form表单中有enctype="multipart/form-data"属性 ，只能通过一下方法获取前台字段名
                    //getFieldName是获取普通表单字段的Name值
                    String fileItemName = fileItem.getFieldName();
                    String imgName = null;
                    //判断前台字段   是普通form表单字段，还是文件字段
                    //request.getParameter()  --  fileItem.getString()
                    //判断是否是  普通form表单字段
                    if (fileItem.isFormField()) {
                        //根据name属性  判断fileItem是imgName还是 image
                        if (fileItemName.equals("imgName")) {
                            imgName = fileItem.getString("UTF-8");
                        }else {
                            System.out.println("其他字段……");
                        }
                        //image
                    }else {
                        //文件上传
                        //先拿文件名  getName()是获取文件名
                        String fileName = fileItem.getName();
                        String ext = fileName.substring(fileName.indexOf(".")+1);
                        if (!(ext.equals("png") || ext.equals("gif") || ext.equals("jpg"))){
                            response.getWriter().println("文件类型有误！格式只能是png gif jpg");
                            return;//终止
                        }
                        //获取文件的内容，并上传
                        //定义文件路径：指定上传的位置
                        //获取服务器路径
                        String path = request.getSession().getServletContext().getRealPath("images");
                        //把获取到的文件路径和文件名放到一个文件对象file中
                        System.out.println(path);
                        File file = new File(path,fileName);
                        //上传文件
                        fileItem.write(file);
                        response.getWriter().println(fileName + "上传成功！");
                        response.sendRedirect("/listBookServlet");
                        return;
                    }
                }
            } catch (FileUploadBase.FileSizeLimitExceededException e){
                e.printStackTrace();
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
